<template>
  <view class="animated fadeIn faster page-bg">
    <view class="bg">
      <view class="head " @click="goUrl('/subPages/homePage/homePage')">
        <image class="img"
               :src="avatar"/>
      </view>
    </view>
    <view class="mt-7 px-2 pt-5 text-center font36 font-bold">{{ name }}
      <text class="iconfont icon-nansheng"
            style="color: #1296db;"></text>
    </view>
    <view class="d-flex videoBtnView d-flex-around my-5 px-2 mt-2 d-flex-center">
      <view v-if="voice_introduce"
            class="voice-btn d-flex d-flex-middle d-flex-center px-3 py-1 rounded20 font22  "
            @click="placeOrder(videoFlag,voice_introduce)">
        <text class="saying mr-1 font28 colorfff"
              :class="videoFlag?'iconfont icon-saying':'iconfont icon-Gc_10_face-PlayCircle'"></text>
      </view>
    </view>
    <view class="text-clamp-two font28 my-1  px-4 my-4 text-center color999">{{characters_introduce
      }}
    </view>


    <view class="m-2 p-2  bg-fff rounded10 ">
      <view class="d-flex  d-flex-middle d-flex-between pt-2 pb-2 bBorder" @click="openModal">
        <view class="font26">
          <text class="color666">品类：</text>
        </view>
        <view class="d-flex-item py-1-5 px-1 text-right">
          <text
              :class="{'colorhold':game_name == ''}">{{ game_name == '' ? '请选择游戏' : game_name }}
          </text>
        </view>
        <text class="iconfont icon-youjiantou color999 mr-1"></text>
      </view>

      <view class="d-flex  d-flex-middle d-flex-between pt-2 pb-2 bBorder">
        <view class="font26">
          <text class="color666">费用：</text>
        </view>
        <view class="d-flex-item py-1-5 px-1 text-right">
          <text class="colorf00">{{ skill_price}}元</text> <text class="color999">/小时</text>
        </view>
<!--        <text class="iconfont icon-youjiantou color999 mr-1"></text>-->
      </view>



      <view class="d-flex d-flex-middle d-flex-between pt-2 pb-2 bBorder">
        <view class="font26">
          <text class="color666">单数：</text>
        </view>
        <view class="number-controller">
          <view
              class="control-btn-alt minus-btn-alt"
              :class="{disabled: formData.num <= 1}"
              @click="decrement"
          >
            <text>-</text>
          </view>
          <view class="number-display">
            <input
                type="digit"
                class="number-input"
                :value="formData.num"
                @input="onInput"
                confirm-type="done"
            />
          </view>
          <view class="control-btn-alt plus-btn-alt" @click="increment">
            <text>+</text>
          </view>
        </view>
      </view>


      <view class="d-flex d-flex-middle pt-2 pb-2 d-flex-center" @click="()=>isSelected = !isSelected">
        <text class="iconfont font30 mr pr-1"
              :class="isSelected?'icon-xuanzhong1 main-color':'icon-gouxuan1 color666'"></text>
        <text>本人已成年，已知晓禁止未成年下单</text>
      </view>

    </view>

    <view class="mx-2 p-2 d-flex  d-flex-between bg-fff rounded10">
      <view class="font26 " style="width: 80rpx;">
        <text class="color666">备注：</text>
      </view>
      <textarea class="note-textarea d-flex-item" placeholder="选填：可备注游戏id，yy号等" v-model="formData.remark"
                :maxlength="200"></textarea>
    </view>

    <view class="d-flex d-flex-center pb-5 p-2 fixed-bottom-container" @click="openPay">
      <view class="money-sure-btn-bg bgcolor598dfc  colorfff d-flex-item font30 p-2 text-center rounded30">
        下单
      </view>
    </view>

    <!-- 选择游戏 -->
    <uni-popup ref="drawerVisible" :safe-area="false" type="bottom" style="position: relative;z-index: 999991;">
      <view class="bg-fff py-4 pb-5 px-2">
        <view class="d-flex d-flex-between">
          <text></text>
          <text class="font32 ml-2">选择游戏</text>
          <text @click="$refs.drawerVisible.close()">取消</text>
        </view>
        <view class=" py-1  category d-flex my-4  d-flex-middle d-flex-wrap ">
          <view v-for="(item,inde) in categoryList" @click="onCategory(item,inde)" :key="inde+'c'"
                style="width: 20%" class="d-flex-column d-flex-middle my-1">
            <view class="cate rounded20" :class="{'cateActive':categoryIndex == inde}">
              <image :src="item.icon" class="rounded20 cateImg"></image>
            </view>

            <text class="font24 mt-1">{{ item.name }}</text>
          </view>
        </view>
        <view class="d-flex d-flex-center pb-5 m-2" @click="closeModal">
          <view class="money-sure-btn-bg bgcolor598dfc colorfff d-flex-item font30 p-2 text-center rounded30">
            确认选择
          </view>
        </view>
      </view>
    </uni-popup>

    <uni-popup ref="payPopup" :safe-area="false"  @touchmove.stop.prevent="moveHandle" type="bottom"
               style="position: relative;z-index: 999991;">
      <view class="wrap">
        <view class="py-3 d-flex d-flex-between d-flex-middle mb-3">
          <view style="width: 150rpx;"></view>
          <text class="font30 color000">立即支付</text>
          <view class="d-flex d-flex-middle d-flex-end pr-3" style="width: 120rpx;">
            <text
                class="iconfont icon-cuo font30 color999" @click="closePayPopup"></text>
          </view>
        </view>
        <view class="pb-4">
          <!-- #ifndef MP-WEIXIN -->
          <view class="d-flex d-flex-between d-flex-middle px-3 mb-4" @click="changePay(1)">
            <view class="d-flex d-flex-middle">
              <image class="rounded"
                     src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/appUpload/20241228140259-f541dd69-c75e-43ad-a9e9-7aa92250dc3c.png"
                     style="width: 50rpx;height: 50rpx;"></image>
              <text class="ml-1">微信支付</text>
            </view>
            <text class="iconfont font36"
                  :class="payType == 1?'main-color icon-xuanzhong1':'colorhold icon-gouxuan1'"></text>
          </view>
          <view class="d-flex d-flex-between d-flex-middle px-3 mb-4" @click="changePay(2)">
            <view class="d-flex d-flex-middle">
              <image class="rounded"
                     src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/appUpload/20241228135921-cfaf5d4f-f4f2-4978-988d-5a1c9b0e7b96.png"
                     style="width: 50rpx;height: 50rpx;"></image>
              <text class="ml-1">支付宝支付</text>
            </view>
            <text class="iconfont font36"
                  :class="payType == 2?'main-color icon-xuanzhong1':'colorhold icon-gouxuan1'"></text>
          </view>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN -->
          <view class="d-flex d-flex-between d-flex-middle px-3 mb-4" @click="changePay(1)">
            <view class="d-flex d-flex-middle">
              <image class="rounded"
                     src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/appUpload/20241228140259-f541dd69-c75e-43ad-a9e9-7aa92250dc3c.png"
                     style="width: 50rpx;height: 50rpx;"></image>
              <text class="ml-1">微信支付</text>
            </view>
            <text class="iconfont font36"
                  :class="payType == 1?'main-color icon-xuanzhong1':'colorhold icon-gouxuan1'"></text>
          </view>
          <!-- #endif -->
          <view class="d-flex d-flex-between d-flex-middle px-3 mb-5" @click="changePay(2)">
            <view class="d-flex d-flex-middle">
              <image class="rounded"
                     src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/pay_wap.png"
                     style="width: 50rpx;height: 50rpx;"></image>
              <text class="ml-1 mr-1">余额支付</text>
              <text class="font22 colorhold">￥{{ balance }}</text>
            </view>
            <text class="iconfont font36"
                  :class="payType == 2?'main-color icon-xuanzhong1':'colorhold icon-gouxuan1'"></text>
          </view>
          <view class="px-5">
            <view style="height: 70rpx;border-radius: 50rpx;"
                  class="bg-main d-flex d-flex-center d-flex-middle" @click="confirmPay">
              <text class="font30 colorfff">确认支付</text>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import {homeApi} from "@/http/homeApi";
import {mapState} from "vuex";
import pay from "@/mixins/pay";

export default {
  mixins: [pay],
  data() {
    return {
      noteContent: '',
      isSelected: false,
      categoryList: [],
      categoryIndex: -1,
      categoriesData: {},
      game_name: '',
      avatar: '',
      formData: {
        game_id: '',
        player_id: '',
        num: 1,
        remark: ''
      },
      payType: '',
      name: "",
      videoFlag: false,
      voice_introduce: "",
      characters_introduce:'',
      skill_price:''
    }
  },
  computed: {
    ...mapState({
      balance: state => state.balance,
      user_id: state => state.id,
      loginState: state => state.loginState,
    })
  },
  onLoad(data) {
    let option = JSON.parse(decodeURIComponent(data.data))
    console.log(option,'option')
    if (option.game_name) {
      this.formData.game_id = option.game_id;
      this.game_name = option.game_name;
    }
    this.formData.player_id = option.user_id;
    this.name = option.name
    this.avatar = option.avatar;
    this.voice_introduce = option.voice_introduce
    this.characters_introduce = option.characters_introduce
    this.skill_price = option.skill_price
    this.categories();
  },
  methods: {
    async categories() {
      let params = {
        play_id: this.formData.player_id
      }
      let res = await homeApi.getHandGame(params)
      this.categoryList = res
    },
    onCategory(data, index) {
      this.categoriesData = data
      this.categoryIndex = index
    },
    increment() {
      this.formData.num++
    },
    decrement() {
      if (this.formData.num > 1) {
        this.formData.num--
      }
    },
    onInput(e) {
      console.log(e, 'ddd')
      const value = e.detail.value.trim()
      if (value === '') {
        this.formData.num = 1
        return
      }

      const num = parseInt(value)
      if (!isNaN(num) && num >= 1) {
        this.formData.num = num
      }
    },
    openModal(e) {
      this.$refs.drawerVisible.open()
    },
    closeModal() {
      this.$refs.drawerVisible.close()
      this.game_name = this.categoriesData.name;
      this.formData.game_id = this.categoriesData.id;
    },
    async openPay() {
      // 检查是否已勾选成年确认
      if (!this.isSelected) {
        uni.showToast({
          title: '本平台严禁未成年下单，若已成年请勾选！',
          icon: 'none',
          duration: 3000,
        });
        return;
      }
      // 检查是否已选择游戏
      if (!this.formData.game_id) {
        uni.showToast({
          title: '请选择游戏',
          icon: 'none'
        });
        return;
      }

      this.$refs.payPopup.open()
    },
    async confirmPay() {
      let that = this
      try {
        uni.showLoading({
          title: '订单创建中...'
        })
        const order = await homeApi.orderPlay(this.formData);
        uni.hideLoading()
        if (order) {
          that.clientTransferPay(order)
        }
      } catch (error) {
        console.log('error', error)
      }
    },
    changePay(number) {
      this.payType = number
    },
    moveHandle() {
      return false
    },
    placeOrder(flag,voice_introduce) {
      if (this.videoFlag) {
        this.stopVoiceIntroduction();
      } else {
        // 如果当前没有播放，则开始播放
        this.videoFlag = true;
        this.playVoiceIntroduction(voice_introduce);
      }
    },

// 播放语音介绍
    playVoiceIntroduction(voiceUrl) {
      if (!voiceUrl) {
        uni.showToast({
          title: '暂无语音介绍',
          icon: 'none'
        });
        this.videoFlag = false;
        return;
      }

      // 如果有正在播放的音频，先停止
      if (this.currentAudioContext) {
        this.currentAudioContext.destroy();
      }

      // 创建音频上下文
      this.currentAudioContext = uni.createInnerAudioContext();

      // 设置音频地址
      this.currentAudioContext.src = voiceUrl;

      // 监听播放事件
      this.currentAudioContext.onPlay(() => {
        console.log('开始播放语音介绍');
      });

      // 监听播放结束事件
      this.currentAudioContext.onEnded(() => {
        console.log('语音介绍播放结束');
        this.resetVoiceState();
      });

      // 监听播放错误事件
      this.currentAudioContext.onError((res) => {
        console.error('语音播放失败', res);
        uni.showToast({
          title: '语音播放失败',
          icon: 'none'
        });
        this.resetVoiceState();
      });

      // 开始播放
      this.currentAudioContext.play();
    },

// 偪止播放语音介绍
    stopVoiceIntroduction() {
      if (this.currentAudioContext) {
        this.currentAudioContext.stop();
        this.currentAudioContext.destroy();
        this.currentAudioContext = null;
      }
      this.resetVoiceState();
    },

// 重置语音播放状态
    resetVoiceState() {
      this.videoFlag = false;
    },

    goUrl(urlPages) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }, 1500)
      } else {
        uni.navigateTo({
          url: urlPages
        })
      }
    },
  },
  beforeDestroy() {
    // 页面销毁时停止并清理音频资源
    if (this.currentAudioContext) {
      this.currentAudioContext.stop();
      this.currentAudioContext.destroy();
      this.currentAudioContext = null;
    }
  },
}
</script>


<style scoped>
.bg {
  width: 100%;
  height: 200rpx;
  position: relative;
}

.head {
  width: 190rpx;
  height: 190rpx;
  position: absolute;
  bottom: -30%;
  left: 36%;
  border: 20rpx solid rgba(255, 255, 255, .3);
  border-radius: 50%;
  overflow: hidden;
}

.head .img {
  width: 100%;
  height: 100%;
}


.bgcolor598dfc {
  background-color: #598dfc;
}


.number-input {
  max-width: 150rpx;
  font-size: 40rpx;
  font-weight: bold;
  color: #598dfc;
  text-align: center;
  width: 100%;
  background: transparent;
  border: none;
  outline: none;
}


.bBorder {
  border-bottom: 2rpx solid rgba(89, 141, 252, .1);
}

.cateActive {
  background: #aec8ff;
  border: 10rpx solid #aec8ff;
}

.cate {
  width: 84rpx;
  height: 84rpx;
  overflow: hidden;
  border: 8rpx solid transparent;
}

.cateImg {
  width: 84rpx;
  height: 84rpx;
}

.number-controller {
  display: flex;
  align-items: center;
  height: 60rpx;
  border-radius: 30rpx;
  overflow: hidden;
  border: 1rpx solid #e0e0e0;
}


.number-display {
  min-width: 100rpx;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
}

.number-input {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  text-align: center;
  width: 100%;
  background: transparent;
  border: none;
  outline: none;
}

.control-btn-alt {
  width: 60rpx;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f8f9fa;
  font-size: 36rpx;
  font-weight: 500;
  color: #598dfc;
  transition: all 0.2s ease;
}

.control-btn-alt:active {
  background-color: #e9ecef;
}

.control-btn-alt.disabled {
  background-color: #f0f0f0;
  color: #cccccc;
  opacity: 0.6;
}


.fixed-bottom-container {
  position: fixed;
  bottom: 20rpx;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 20rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);
  z-index: 999;
}

.videoBtnView {
  position: relative;
}

.voice-btn {
  position: absolute;
  bottom: -36rpx;
  background: linear-gradient(135deg, #a6c0fe, #f68084);
  border: none;
  color: #ffffff;
  box-shadow: 0 4rpx 12rpx rgba(74, 105, 189, 0.3);
  transition: all 0.3s ease;
  border-radius: 20rpx;
  padding: 8rpx 65rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.voice-btn:hover {
  background: linear-gradient(135deg, #a6c0fe, #f68084);
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 16rpx rgba(74, 105, 189, 0.4);
}

/* 录音中状态 */
.voice-btn-recording {
  background: linear-gradient(135deg, #e55039, #eb2f06);
  animation: pulse 1.5s infinite;
}


@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(255, 107, 107, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10rpx rgba(255, 107, 107, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(255, 107, 107, 0);
  }
}

.saying {
  font-size: 28rpx;
}

.icon-Gc_10_face-PlayCircle {
  font-size: 28rpx;
}

.icon-saying {
  animation: voiceAnimate 1s infinite;
}

@keyframes voiceAnimate {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}

.mr-1 {
  margin-right: 10rpx;
}


.saying {
}

.mr-1 {
  margin-right: 10rpx;
}

</style>